package org.classg.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.classg.edu.client.VodClient;
import org.classg.edu.entity.Video;
import org.classg.edu.mapper.VideoMapper;
import org.classg.edu.service.VideoService;
import org.classg.servicebase.exception.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-05-18
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    // 根据课程id删除小节（需要删除视频）
    @Override
    public void deleteVideoByCourseId(String id) {
        List<String> list = new ArrayList<>();
        // 需要删小节内部的视频
        List<Video> videos = baseMapper.selectList(new LambdaQueryWrapper<Video>().eq(Video::getCourseId, id));
        for (Video video : videos) {
            String videoId = video.getVideoSourceId();
            if (!StringUtils.isEmpty(videoId)) {
                list.add(videoId);
            }
        }
        vodClient.deleteVideoByVideoIds(list);
        int temp = baseMapper.delete(new LambdaQueryWrapper<Video>().eq(Video::getCourseId, id));
        if (temp <= 0) {
            throw new MyException(20001, "根据课程id删除小节失败！");
        }
    }

    // 根据小节id删除小节（同时要把视频删除）
    @Override
    public void deleteVideoById(String id) {
        // 删除视频
        Video video = baseMapper.selectById(id);
        if (!StringUtils.isEmpty(video.getVideoSourceId())) {
            vodClient.deleteVideoByVideoId(video.getVideoSourceId());
        }
        // 删除小节
        Integer temp = baseMapper.deleteById(id);
        if (temp == null && temp <= 0) {
            throw new MyException(20001, "根据小节id删除小节失败！");
        }
    }

}
